<template>
  <!-- <a-button type="primary" @click="showDrawer">Open</a-button> -->
  <a-drawer v-model:visible="vdata.visible" width="40%" :mask-closable="false" @close="close">
    <template #title>
      <div
        style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
      >
        <span>导入名单</span>
        <!-- <a-button type="link" @click="exportCode(vdata.record)">导出渠道</a-button> -->
      </div>
    </template>

    <div class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="fileList">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <a-button class="item" type="link" style="padding: 4px 0" @click="merchantTemplate">
                  <!-- <template v-if="vdata.saveObject.channelType === 0"
                      >机构渠道模板下载</template> -->
                  导入名单模板下载
                  <!-- <template>导入名单模板下载</template> -->
                  <!-- <template v-else>其他渠道模板下载</template> -->
                </a-button>
              </template>
              <a-upload-dragger
                v-model:fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 选择是哪个商户，商户渠道 -->
        <div class="textMerchant">
          <!-- 写上传组件 -->
          <!-- <GzUploadExe @sendData="getData" /> -->
        </div>
      </a-form>
      <!-- 列表展示 -->
      <GzTable
        ref="infoTableRef"
        :table-columns="tableColumns"
        :pagination="true"
        :req-table-data-func="reqTableDataFunc"
        :scrollX="600"
        :dataSource="resultList"
      >
        <template #topBtnSlot>
          <!-- <b>渠道列表</b> -->
          <!-- <a-button
              type="primary"
              @click="exportCode"
              :disabled="resultList.length == 0 ||exportList.length ==0" 
            >
              <export-outlined />导出渠道码
            </a-button> -->
        </template>
        <template #bodyCell="{ record, column }">
          <template v-if="column.key === 'channelType'">
            {{
              record.channelType === 0
                ? "机构渠道"
                : record.channelType === 1
                  ? "商户渠道"
                  : "其他渠道"
            }}
          </template>
          <template v-if="column.key === 'operation'">
            <a-switch
              :checked="record.isDeleted === 0"
              @change="changeStatus(record.activityChannelId, record.isDeleted)"
            />
          </template>
        </template>
      </GzTable>
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, defineExpose } from 'vue'
import * as XLSX from 'xlsx'
import {
  req,
  $getUploadFormParams,
  API_URL_ACTIVITY_CHANNEL_DELETE,
  API_ACTIVITY_ASSIGNIMPORT
} from '@/api/manage'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const infoTableRef = ref()
const formRef = ref()
// 数据源
const vdata: any = reactive({
  fileList: [], //上传文件列表
  saveObject: {
    channelType: 1, //渠道类型
    isDistanceLimit: false,
  },
  visible: false, //是否显示
  action: '', //上传地址
})
// 列表表头
const tableColumns = [
  { key: 'phone', title: '手机号', dataIndex: 'phone' },
  { key: 'result', title: '导入结果', dataIndex: 'result' },
]

const rules: any = {
  fileList: [{ required: true, message: '请上传文件', trigger: 'change' }],
  agentNo: [{ required: true, message: '请选择机构', trigger: 'change' }],
  channelName: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
  channelCode: [{ required: true, message: '请输入商户号', trigger: 'blur' }],
  distanceLimit: [{ required: true, message: '请输入距离', trigger: 'blur' }],
}


/**
 * 渠道上下线
 */
function changeStatus(activityChannelId, isDeleted) {
  let message = isDeleted === 0 ? '下线' : '上线'
  isDeleted = isDeleted === 0 ? 1 : 0
  $infoBox.confirmDanger(
    `确认${message}？`,
    `请确认是否${message}当前渠道？`,
    () => {
      req
        .add(API_URL_ACTIVITY_CHANNEL_DELETE, { activityChannelId, isDeleted })
        .then(() => {
          $infoBox.message.success(`${message}成功`)
          // 刷新列表
          infoTableRef.value.refTable()
        })
    }
  )
}

/**
 * 展开
 */
async function show(record) {
  vdata.saveObject = {
    activityId: record.activityId
  }
  vdata.visible = true
}

function close() {
  vdata.visible = false
}

defineExpose({
  show,
})

/**
 * 文件上传
 */
function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'yx').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.saveObject.ossFileUrl = res.ossFileUrl
  })
}
function uploadChange(info) {
  console.log('info', info)
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功
    complete()
  }
}
const exportList = ref([])
const resultList = ref([])

// 完成
function complete() {
  formRef.value
    .validate()
    .then(() => {
      req
        .add(API_ACTIVITY_ASSIGNIMPORT, {
          activityId: vdata.saveObject.activityId,
          ossFileUrl: vdata.saveObject.ossFileUrl
        })
        .then((res, error) => {
          console.log(res)
          exportList.value = res.export
          resultList.value = res
          $infoBox.message.success('新增成功')
        })
    })
    .catch(() => { })
}

// excel表格导出函数数据
const exportToExcel = (item, name) => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet([...item])

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, `${name}.xlsx`)
}
// 商户模板下载
function merchantTemplate() {
  const { channelType } = vdata.saveObject
  let tempalteInformation: any = undefined
  let tempalteName: any
  tempalteName = '导入名单模板'
  tempalteInformation = [
    ['手机号',],
    ['1xxxxxxx',],
  ]
  exportToExcel(tempalteInformation, tempalteName)
}
</script>
<style lang="less" scoped>
.choseText {
  color: #1890ff;
}

.container {
  width: 100%;
  padding-bottom: 30px;

  .step {
    width: 30%;
  }

  .textMerchant {
    width: 60%;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .merchantResult {
    .information {
      display: flex;
      justify-content: right;
      margin-top: 30px;
    }
  }

  .form {
    margin: 30px;
    justify-content: center;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }
  }
}

/deep/ .ant-upload-list-item-name {
  width: auto;
  flex-grow: 1 !important;
}
</style>